<?php
class DataToValueModel extends BaseModel
{

	var $tables = array('rule'=>'data_to_user_rule', 'value'=>'data_to_user_value');


	function &instance() {
		static $registry;
		if (!$registry) { $registry = &new DataToValueModel(); }
		return $registry;
	}	
	
	
	function getRuleId($rule) {
		$sql = "SELECT id FROM {$this->tbl->rule} d WHERE d.title = '{$rule}'";
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		return $result->Fields('id');
	}
	
	
	function &getDataByIds($record_ids, $rule, $table, $fields, $index = 0) {
	
		
	} 
	
	// get assigned ids for value($record_id)
	// record id  could be array
	function getDataIds($rule, $record_id = false) {
		
		$params = ($record_id) ? "dv.data_value IN ($record_id)" : 1;
		
		$sql = "
		SELECT 
			dv.*
		FROM 
			{$this->tbl->rule} dr,
			{$this->tbl->value} dv
		WHERE 1
			AND dr.title = '{$rule}'
			AND dr.id = dv.rule_id
			AND {$params}";
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		$data = array();
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		while($row = $result->FetchRow()) {
			$data[$row['data_value']][] = $row['user_value'];
		}
		
		return $data;
	}
	
	
	function &getDataById($record_id, $rule, $table, $table_field, $select, $one_to_many = false) {
		
		$sql = "
		SELECT 
			{$select}
		FROM 
			{$this->tbl->rule} dr,
			{$this->tbl->value} dv,
			{$table}
		WHERE 1
			AND dr.title = '{$rule}'
			AND dr.id = dv.rule_id
			AND dv.data_value IN ($record_id)
			AND dv.user_value = {$table_field}";
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		
		if($one_to_many) {
			$data = array();
			while($row = $result->FetchRow()) {
				$data[$row['k']][] = $row['v'];
			}
		} else {
			$data = $result->GetAssoc();
		}
		
		return $data;
	}		
	
	
	function saveData($data, $record_id, $rule) {
		
		if(!$data) { return; }
		
		require_once 'eleontev/SQL/MultiInsert.php';
		
		$rule_id = $this->getRuleId($rule);
		foreach($data as $k => $v) {
			$_data[] = array($v);
		}
		
		$ins = new MultiInsert;
		$ins->setFields('user_value', array('rule_id', 'data_value'));
		$ins->setValues($_data, array($rule_id, $record_id));
		$sql = $ins->getSql($this->tbl->value);
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		//exit;
		
		return $this->db->Execute($sql) or die(db_error($sql));
	}
	
	
	function deleteData($record_id, $rule) {
		
		$rule_id = $this->getRuleId($rule);
		$sql = "DELETE FROM {$this->tbl->value} 
		WHERE rule_id = '{$rule_id}' AND data_value = '{$record_id}'";
		
		return $this->db->Execute($sql) or die(db_error($sql));
	}
}
?>